<template>
    <Header />
    <div class="project-container">
        <!-- 主要内容区域 -->
        <div class="main-content">
            <!-- 左侧导航栏 -->
            <Sidebar ref="sidebarRef" :sidebar-width="sidebarWidth" :min-width="minWidth"
                @dashboard-home="navigateDashboard" @click-api="handleClickApi" @navigate-home="navigateHome"
                @add-api="handleAddApi" />
            <!-- 拖拽分隔线 -->
            <ResizeHandle :sidebar-width="sidebarWidth" :min-width="minWidth" :is-resizing="isResizing"
                @start-resize="startResize" @reset-width="resetWidth" />
            <!-- 主要内容区域 -->
            <div class="detail-area">
                <router-view v-if="route.params.apiId" />
                <DefaultPage v-else />
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, provide, watch, computed } from 'vue';
import { useRoute } from 'vue-router';
import router from '@/router';
import { ElMessageBox } from 'element-plus';
import Sidebar from './components/Sidebar.vue';
import ResizeHandle from './components/ResizeHandle.vue';
import Header from '@/common/components/Header.vue';
import DefaultPage from './components/DefaultPage.vue';
import { useProjectStore } from '@/store/modules/project';
import { useUserStore } from "@/store/modules/user.ts";
import { useEditorStore } from "@/store/modules/editStatus.ts";

// 常量定义
const SIDEBAR_CONFIG = {
    DEFAULT_WIDTH: 380,
    MIN_WIDTH: 320,
    MAX_WIDTH: 600,
    RESET_WIDTH: 380
};

// 组件状态
const route = useRoute();
const projectStore = useProjectStore();
const userStore = useUserStore();
const editorStore = useEditorStore();

// 响应式状态
const sidebarWidth = ref(SIDEBAR_CONFIG.DEFAULT_WIDTH);
const isResizing = ref(false);
const sidebarRef = ref();

// 计算属性
const projectId = computed(() => Number(route.params.id));
const minWidth = computed(() => SIDEBAR_CONFIG.MIN_WIDTH);
const isAddMode = computed(() => route.query.mode === 'add');

// 处理未保存更改的确认
const confirmLoseChanges = async () => {
    if (!editorStore.hasUnsavedChanges) {
        return true;
    }

    try {
        await ElMessageBox.confirm(
            '您有未保存的更改，切换后将丢失，是否继续？',
            '提示',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }
        );
        editorStore.setHasUnsavedChanges(false);
        return true;
    } catch {
        return false;
    }
};

// 处理添加API
const handleAddApi = async (dataRef) => {
    try {
        await router.push({
            name: 'api-detail',
            params: {
                id: projectId.value,
                apiId: Number(route.params.apiId) || 0
            },
            query: {
                mode: 'add',
                moduleId: dataRef.id
            }
        });
    } catch (error) {
        console.error('导航到添加API页面失败:', error);
    }
};

// 处理点击API
const handleClickApi = async (id) => {
    if (!await confirmLoseChanges()) return;

    try {
        await router.push({
            name: 'api-detail',
            params: {
                id: projectId.value,
                apiId: id
            },
            query: { mode: 'view' }
        });
    } catch (error) {
        await router.push('/403');
    }
};

// 导航到首页
const navigateHome = async () => {
    if (!await confirmLoseChanges()) return;

    try {
        await router.push('/home');
    } catch (error) {
        console.error('导航到首页失败:', error);
    }
};

// 导航到仪表板
const navigateDashboard = async () => {
    if (!await confirmLoseChanges()) return;

    try {
        await router.push(`/project/${projectId.value}/admin-panel`);
    } catch (error) {
        console.error('导航到仪表板失败:', error);
    }
};

// 开始拖拽调整宽度
const startResize = (e) => {
    e.preventDefault();

    isResizing.value = true;
    document.body.style.userSelect = 'none';
    document.body.style.cursor = 'col-resize';

    const startX = e.type === 'mousedown' ? e.clientX : e.touches[0].clientX;
    const startWidth = sidebarWidth.value;

    const handleMouseMove = (e) => {
        if (!isResizing.value) return;

        const currentX = e.type === 'mousemove' ? e.clientX : e.touches[0].clientX;
        const deltaX = currentX - startX;
        const newWidth = startWidth + deltaX;
        const clampedWidth = Math.max(
            SIDEBAR_CONFIG.MIN_WIDTH,
            Math.min(newWidth, SIDEBAR_CONFIG.MAX_WIDTH)
        );
        sidebarWidth.value = clampedWidth;
    };

    const handleMouseUp = () => {
        cleanupResize();
    };

    const cleanupResize = () => {
        isResizing.value = false;
        document.body.style.userSelect = '';
        document.body.style.cursor = '';

        document.removeEventListener('mousemove', handleMouseMove);
        document.removeEventListener('mouseup', handleMouseUp);
        document.removeEventListener('touchmove', handleMouseMove);
        document.removeEventListener('touchend', handleMouseUp);
    };

    document.addEventListener('mousemove', handleMouseMove);
    document.addEventListener('mouseup', handleMouseUp);
    document.addEventListener('touchmove', handleMouseMove);
    document.addEventListener('touchend', handleMouseUp);
};

// 重置侧边栏宽度
const resetWidth = () => {
    sidebarWidth.value = SIDEBAR_CONFIG.RESET_WIDTH;
};

// 防重复调用状态
let isRefreshing = false;

// 刷新侧边栏并定位节点
const refreshSidebarReloadEnd = async (apiId) => {
    if (isRefreshing || !apiId) {
        return;
    }
    isRefreshing = true;
    try {
        await sidebarRef.value?.refreshAndLocateNode({
            id: Number(apiId)
        });
    } catch (error) {
    } finally {
        isRefreshing = false;
    }
};

// 监听路由变化
watch(() => route.params.apiId, async (newApiId) => {
    // 新增模式不触发侧边栏定位
    if (isAddMode.value) {
        return;
    }

    await refreshSidebarReloadEnd(newApiId);
}, { immediate: false });

// 提供给子组件的刷新方法
provide('refreshSidebar', refreshSidebarReloadEnd);

// 处理浏览器关闭/刷新时的未保存更改
const handleBeforeUnload = (e) => {
    if (editorStore.hasUnsavedChanges) {
        e.preventDefault();
        e.returnValue = '';
    }
};

// 初始化项目数据
const initializeProject = async () => {
    try {
        await Promise.all([
            projectStore.setProjectInfo(projectId.value),
            projectStore.setUserProjectInfo(userStore.getUserInfo()?.id, projectId.value)
        ]);
    } catch (error) {
        console.error('初始化项目数据失败:', error);
    }
};

// 初始化API数据
const initializeApi = async () => {
    if (!route.params.apiId) {
        return;
    }

    try {
        await sidebarRef.value?.refreshAndLocateNode({
            id: Number(route.params.apiId),
            isReload: false
        });
    } catch (error) {
    } finally {
    }
};

// 组件挂载
onMounted(async () => {
    window.addEventListener('beforeunload', handleBeforeUnload);

    await initializeProject();
    await initializeApi();
});

// 组件卸载
onUnmounted(() => {
    window.removeEventListener('beforeunload', handleBeforeUnload);

    // 清理拖拽事件监听器（如果存在）
    document.removeEventListener('mousemove', () => { });
    document.removeEventListener('mouseup', () => { });
    document.removeEventListener('touchmove', () => { });
    document.removeEventListener('touchend', () => { });
});
</script>

<style lang="less" scoped>
// 未保存更改提示
.unsaved-changes-alert {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    background: var(--warning-color);
    color: white;
    padding: 12px 24px;
    z-index: 1000;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    animation: slideDown 0.3s ease-out;

    .alert-content {
        display: flex;
        align-items: center;
        gap: 8px;
        justify-content: center;
        font-size: 14px;
        font-weight: 500;

        i {
            font-size: 16px;
        }
    }
}

@keyframes slideDown {
    from {
        transform: translateY(-100%);
        opacity: 0;
    }

    to {
        transform: translateY(0);
        opacity: 1;
    }
}

// 项目容器
.project-container {
    background: var(--bg-primary);
    height: calc(100vh - 64px);
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
    padding: 0;
    margin: 0;
    overflow: hidden;
}

// 主要内容区域
.main-content {
    display: flex;
    height: 100%;
    overflow: hidden;
}

// 详情区域
.detail-area {
    flex: 1;
    overflow: hidden;
}

// 默认页面
.default-page {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    background: var(--bg-primary);
    padding: 40px;
}

.default-content {
    text-align: center;
    max-width: 400px;
}

.default-icon {
    margin-bottom: 24px;

    i {
        font-size: 64px;
        color: var(--text-secondary);
        opacity: 0.6;
    }
}

.default-title {
    font-size: 24px;
    font-weight: 600;
    color: var(--text-primary);
    margin-bottom: 12px;
    line-height: 1.4;
}

.default-description {
    font-size: 16px;
    color: var(--text-secondary);
    line-height: 1.6;
    margin: 0;
}
</style>
